package com.yanqu.road.server.cmd.activity;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.rank.UnionRankMsgModel;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.PeakStrongholdWarProto;
import com.yanqu.road.pb.rank.RankProto;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.CommonActivityRankMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Cmd(code = Protocol.S_PEAK_UNION_MAX_ABILITY_RANK_UPDATE, desc = "排行数据更新")
public class PeakActivityUnionMaxAbilityRankUpdateCmd extends AbstractCommand {

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        CrossUnionProto.CrossUnionGetMaxAbilityUnionRankListResp respMsg = CrossUnionProto.CrossUnionGetMaxAbilityUnionRankListResp.parseFrom(packet.getBytes());
        int activityId = respMsg.getActivityId();
        ActivityInfo activityInfo = ActivityMgr.getOpenActivityInfo(activityId);
        if (activityInfo == null) {
            log.error("报名期榜单返回后没有活动{}", activityId);
            return;
        }
        int groupId = respMsg.getGroupId();
        UnionRankMsgModel model = CommonActivityRankMgr.getUnionRankMsgModelByGroup(activityId, groupId);
        if (null != model) {
            model.setUpdateTime(respMsg.getUpdateTime());
            RankProto.UnionRankListMsg.Builder listMsg = RankProto.UnionRankListMsg.newBuilder();
            for (CrossUnionProto.CrossUnionActivityLockRankTemp rankTemp : respMsg.getRankList()) {
                RankProto.UnionRankTempMsg.Builder rankMsg = RankProto.UnionRankTempMsg.newBuilder();
                rankMsg.setUnionUid(rankTemp.getUnionUid());
                rankMsg.setUnionBaseData(rankTemp.getUnionBase());
                rankMsg.setValue(rankTemp.getTotalAbility());
                listMsg.addRankList(rankMsg);
            }
            model.setRankListMsg(listMsg);

            for (CrossUnionProto.UnionMemberIdsTemp unionMemberIdsTemp : respMsg.getUnionMemberIsList()) {
                model.updateMemberIds(unionMemberIdsTemp.getUnionId(), unionMemberIdsTemp.getMemberIdsList());
            }

            //同步给请求了旧数据的玩家
            List<Long> syncUserIds = model.getSynUserIds();
            boolean isGroupType = UnionActivityGroupHelper.isGroupActivityType(activityInfo.getType());
            if (!syncUserIds.isEmpty()) {
                RankProto.UnionRankListMsg rankListMsg = model.getRankListMsg();
                if (activityInfo.getType() == eActivityType.PeakStrongHold.getValue()) {
                    sendToPeakStrongAbilityRank(activityId, syncUserIds, rankListMsg, isGroupType);
                } else {
                    RankProto.GetActivityUnionRankListRespMsg.Builder clientMsg = RankProto.GetActivityUnionRankListRespMsg.newBuilder();
                    clientMsg.setActivityId(activityId);
                    clientMsg.setMyValue("0");
                    clientMsg.setMyRank(0);

                    for (Long userId : syncUserIds) {
                        GamePlayer syncPlayer = GamePlayerMgr.getOnlinePlayer(userId);
                        if (null != syncPlayer) {

                            String unionUid = syncPlayer.getUserInfo().getUnionUid();
                            if (isGroupType) {
                                unionUid = GameUnionActivityGroupMgr.getUnionUid(activityId, userId);
                            }
                            boolean isInside = false;
                            int rank = 0;
                            for (RankProto.UnionRankTempMsg rankTempMsg : rankListMsg.getRankListList()) {
                                rank++;
                                if (Objects.equals(rankTempMsg.getUnionUid(), unionUid)) {
                                    clientMsg.setMyValue(rankTempMsg.getValue());
                                    clientMsg.setMyRank(rank);
                                    isInside = true;
                                    break;
                                }
                            }
                            if (!isInside && !StringUtils.isNullOrEmpty(unionUid)) {//不在榜单里,累计游戏服缓存的赚钱
                                Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
                                BigInteger myValue = BigInteger.ZERO;
                                for (CrossUnionMember member : memberMap.values()) {
                                    myValue = myValue.add(member.getHistoryMaxAbility());
                                }
                                clientMsg.setMyValue(myValue.toString());
                            }

                            clientMsg.setRank(rankListMsg);
                            syncPlayer.sendPacket(Protocol.U_PEAK_UNION_MAX_ABILITY_RANK_LIST, clientMsg);
                        }
                    }
                }
            }


            if (model.isNeedSendToActivityCross()) {
                model.setNeedSendToActivityCross(false);

                RankProto.CrossUnionRankListLockMsg.Builder lockMsg = RankProto.CrossUnionRankListLockMsg.newBuilder();
                lockMsg.setActivityId(activityId);
                lockMsg.setGroupId(groupId);
                for (RankProto.UnionRankTempMsg rankTempMsg : model.getRankListMsg().getRankListList()) {
                    RankProto.CrossUnionRankLockTemp.Builder rankLockMsg = RankProto.CrossUnionRankLockTemp.newBuilder();
                    rankLockMsg.setRankTemp(rankTempMsg);
                    model.getMemberServerMap(rankTempMsg.getUnionUid()).forEach((userId, memberTemp) -> {
                        RankProto.CrossUnionMemberTemp.Builder memberMsg = RankProto.CrossUnionMemberTemp.newBuilder();
                        memberMsg.setMemberId(userId);
                        memberMsg.setServerId(memberTemp.getServerid());
                        memberMsg.setPosition(memberTemp.getPosition());
                        memberMsg.setEarnSpeed(memberTemp.getEarnSpeed());
                        memberMsg.setMaxAbility(memberTemp.getMaxAbility());
                        rankLockMsg.addMember(memberMsg);
                    });
                    lockMsg.addRank(rankLockMsg);
                }
                lockMsg.setGroupId(model.getGroupId());
                GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_PEAK_LOCK_REGISTRATION_PROMOTION_UNION,
                        lockMsg, 0, activityId, groupId);
            }
        }

    }

    @Override
    public void sendData(GamePlayer player) {

    }

    public void sendToPeakStrongAbilityRank(int activityId, List<Long> syncUserIds, RankProto.UnionRankListMsg rankListMsg, boolean isGroupType) {
        int rank = 1;

        Map<String, Integer> unionRankMap = new HashMap<>();
        PeakStrongholdWarProto.PeakStrongholdUnionAbilityRankRespMsg.Builder respMsg = PeakStrongholdWarProto.PeakStrongholdUnionAbilityRankRespMsg.newBuilder();
        for (RankProto.UnionRankTempMsg rankTempMsg : rankListMsg.getRankListList()) {
            PeakStrongholdWarProto.UnionAbilityRankTemp.Builder rankMsg = PeakStrongholdWarProto.UnionAbilityRankTemp.newBuilder();
            rankMsg.setRank(rank++);
            rankMsg.setUnionInfo(rankTempMsg.getUnionBaseData());
            rankMsg.setAbility(rankTempMsg.getValue());
            rankMsg.setUnionId(rankTempMsg.getUnionUid());
            respMsg.addRankData(rankMsg);
            unionRankMap.put(rankMsg.getUnionId(), rankMsg.getRank());
        }

        for (Long syncUserId : syncUserIds) {
            GamePlayer syncPlayer = GamePlayerMgr.getOnlinePlayer(syncUserId);
            if (null == syncPlayer) {
                continue;
            }
            String playerUnionId = syncPlayer.getUserInfo().getUnionUid();
            if (isGroupType) {
                playerUnionId = GameUnionActivityGroupMgr.getUnionUid(activityId, syncUserId);
            }
            int ownRank = unionRankMap.getOrDefault(playerUnionId, 0);
            String myValue = "0";
            boolean isInside = ownRank == 0;
            if (!isInside && !StringUtils.isNullOrEmpty(playerUnionId)) {//不在榜单里,累计游戏服缓存的赚钱
                Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(playerUnionId);
                BigInteger unionTotalValue = BigInteger.ZERO;
                for (CrossUnionMember member : memberMap.values()) {
                    unionTotalValue = unionTotalValue.add(member.getHistoryMaxAbility());
                }
                myValue = unionTotalValue.toString();
            }
            respMsg.setValue(myValue);
            respMsg.setOwnRank(ownRank);
            syncPlayer.sendPacket(Protocol.U_PEAK_STRONGHOLD_UNION_ABILITY_RANK, respMsg);
        }
    }
}
